﻿
//

//


using EMSNet.Core.Service;
using Microsoft.AspNetCore.Http;

namespace EMSNet.Service;

/// <summary>
/// 采集点管理服务 🧩
/// </summary>
[ApiDescriptionSettings(ServiceConst.GroupName, Order = 100)]
public class EmsPollingPointService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<EmsPollingPoint> _emsPollingPointRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public EmsPollingPointService(SqlSugarRepository<EmsPollingPoint> emsPollingPointRep, ISqlSugarClient sqlSugarClient)
    {
        _emsPollingPointRep = emsPollingPointRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询采集点管理 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询采集点管理")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<EmsPollingPointOutput>> Page(PageEmsPollingPointInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _emsPollingPointRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.Code.Contains(input.Keyword) || u.Name.Contains(input.Keyword) || u.MonthName.Contains(input.Keyword) || u.Category.Contains(input.Keyword) || u.PollMethod.Contains(input.Keyword) || u.SendType.Contains(input.Keyword) || u.CalMethod.Contains(input.Keyword) || u.TolerancePercent.Contains(input.Keyword) || u.TolerancePercent1.Contains(input.Keyword) || u.IsUsed.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Code), u => u.Code.Contains(input.Code.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.MonthName), u => u.MonthName.Contains(input.MonthName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Category), u => u.Category.Contains(input.Category.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.PollMethod), u => u.PollMethod.Contains(input.PollMethod.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.SendType), u => u.SendType.Contains(input.SendType.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.CalMethod), u => u.CalMethod.Contains(input.CalMethod.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.TolerancePercent), u => u.TolerancePercent.Contains(input.TolerancePercent.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.TolerancePercent1), u => u.TolerancePercent1.Contains(input.TolerancePercent1.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.IsUsed), u => u.IsUsed.Contains(input.IsUsed.Trim()))
            .LeftJoin<EmsDictionary>((u, category) => u.Category == category.code)
            .Select((u, category) => new EmsPollingPointOutput
            {
                Id = u.Id,
                TenantId = u.TenantId,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                CreateOrgId = u.CreateOrgId,
                CreateOrgName = u.CreateOrgName,
                IsDelete = u.IsDelete,
                Code = u.Code,
                Name = u.Name,
                MonthName = u.MonthName,
                Category = u.Category,
                CategoryFkDisplayName = $"{category.name}",
                PollMethod = u.PollMethod,
                SendType = u.SendType,
                CalMethod = u.CalMethod,
                TolerancePercent = u.TolerancePercent,
                TolerancePercent1 = u.TolerancePercent1,
                IsUsed = u.IsUsed,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取采集点管理详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取采集点管理详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<EmsPollingPoint> Detail([FromQuery] QueryByIdEmsPollingPointInput input)
    {
        return await _emsPollingPointRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加采集点管理 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加采集点管理")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddEmsPollingPointInput input)
    {
        var entity = input.Adapt<EmsPollingPoint>();
        return await _emsPollingPointRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新采集点管理 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新采集点管理")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateEmsPollingPointInput input)
    {
        var entity = input.Adapt<EmsPollingPoint>();
        await _emsPollingPointRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除采集点管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除采集点管理")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteEmsPollingPointInput input)
    {
        var entity = await _emsPollingPointRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _emsPollingPointRep.FakeDeleteAsync(entity);   //假删除
        //await _emsPollingPointRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除采集点管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除采集点管理")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteEmsPollingPointInput> input)
    {
        var exp = Expressionable.Create<EmsPollingPoint>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _emsPollingPointRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _emsPollingPointRep.FakeDeleteAsync(list);   //假删除
        //return await _emsPollingPointRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataEmsPollingPointInput input)
    {
        var categoryData = await _emsPollingPointRep.Context.Queryable<EmsDictionary>()
            .InnerJoinIF<EmsPollingPoint>(input.FromPage, (u, r) => u.code == r.Category)
            .Select(u => new {
                Value = u.code,
                Label = $"{u.name}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "category", categoryData },
        };
    }
    
    /// <summary>
    /// 导出采集点管理记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出采集点管理记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageEmsPollingPointInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportEmsPollingPointOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "采集点管理导出记录");
    }
    
    /// <summary>
    /// 下载采集点管理数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载采集点管理数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportEmsPollingPointOutput>(), "采集点管理导入模板", (_, info) =>
        {
            if (nameof(ExportEmsPollingPointOutput.CategoryFkDisplayName) == info.Name) return _emsPollingPointRep.Context.Queryable<EmsDictionary>().Select(u => $"{u.name}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入采集点管理记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入采集点管理记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportEmsPollingPointInput, EmsPollingPoint>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 能源类别
                    var categoryLabelList = pageItems.Where(x => x.CategoryFkDisplayName != null).Select(x => x.CategoryFkDisplayName).Distinct().ToList();
                    if (categoryLabelList.Any()) {
                        var categoryLinkMap = _emsPollingPointRep.Context.Queryable<EmsDictionary>().Where(u => categoryLabelList.Contains($"{u.name}")).ToList().ToDictionary(u => $"{u.name}", u => u.code);
                        pageItems.ForEach(e => {
                            e.Category = categoryLinkMap.GetValueOrDefault(e.CategoryFkDisplayName ?? "");
                            if (e.Category == null) e.Error = "能源类别链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<EmsPollingPoint>>();
                    
                    var storageable = _emsPollingPointRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.Code?.Length > 32, "采集点编号长度不能超过32个字符")
                        .SplitError(it => it.Item.Name?.Length > 32, "采集点名称长度不能超过32个字符")
                        .SplitError(it => it.Item.MonthName?.Length > 32, "采集点名称（月）长度不能超过32个字符")
                        .SplitError(it => it.Item.Category?.Length > 32, "能源类别长度不能超过32个字符")
                        .SplitError(it => it.Item.PollMethod?.Length > 32, "采集方式长度不能超过32个字符")
                        .SplitError(it => it.Item.SendType?.Length > 32, "上报类别长度不能超过32个字符")
                        .SplitError(it => it.Item.CalMethod?.Length > 32, "计算方法长度不能超过32个字符")
                        .SplitError(it => it.Item.TolerancePercent?.Length > 32, "折标系数长度不能超过32个字符")
                        .SplitError(it => it.Item.TolerancePercent1?.Length > 32, "折标系数（计）长度不能超过32个字符")
                        .SplitError(it => it.Item.IsUsed?.Length > 32, "是否可用长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
